import React, { Component } from 'react';
import { StoreProvider } from 'iflux2';
import AppStore from './store.js';

import WebApi from './webapi';

import { Tabs, Pagination } from 'antd';

import Counts from './component/Counts';
import Table from './component/Table';

const TabPane = Tabs.TabPane;

@StoreProvider(AppStore)
export default class Message extends Component {

    constructor(props) {
        super(props);
        this.state = {
            params: {
                page: 1,
                pageSize: 10,
                msgType: 'text',
                cate: 'all'
            },
            data: {
                list: [],
                total: 0
            }
        }
    }

    componentDidMount() {
        this._paging(1);
    }

    render() {
        let { params, data } = this.state;

        return (
            <div className="message">
                <Tabs type="card" onChange={this._tabChange}>
                    <TabPane tab="所有消息" key="all" />
                    <TabPane tab="未回复消息" key="noReply" />
                    <TabPane tab="已收藏消息" key="star" />
                </Tabs>

                <Counts ref="counts" />

                <Table data={data.list} onUpdate={() => this.refs.counts.componentDidMount()} />

                <Pagination
                    current={params.page}
                    pageSize={params.pageSize}
                    defaultCurrent={params.page}
                    defaultPageSize={params.pageSize}
                    total={data.total}
                    onChange={this._paging}
                    onShowSizeChange={this._paging}
                    showSizeChanger
                    showQuickJumper
                />
            </div>
        )
    }

    _tabChange = (cate) => {
        this.state.params.cate = cate;
        this._paging(1);
    }

    _paging = async (page, pageSize = this.state.params.pageSize) => {
        let { params } = this.state;
        Object.assign(params, { page, pageSize });
        let data = await WebApi.paging(params),
            users = (await WebApi.getUsers({
                openid_list: data.list.map(o => o.fromUser)
            })).reduce((p, o) => {
                return p[o.openid] = o, p;
            }, {});
        data.list = data.list.map(o => Object.assign(o, users[o.fromUser]));
        this.setState({ data, params });
    }

}